package com.atgm.mall.gmmallcart.interceptor;

import com.atgm.common.constant.AuthConstant;
import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.exception.CartException;
import com.atgm.common.utils.GmMallUtils;
import com.atgm.common.utils.JwtUtils;
import com.atgm.mall.gmmallcart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CartInterceptor implements HandlerInterceptor{

    public static ThreadLocal<UserInfoTo> toThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录用户的token
        String token = (String) request.getHeader(AuthConstant.TOKEN);
        if (GmMallUtils.isEmpty(token)) {
            throw new CartException("用户没有登录", BizCodeEnume.USER_LOGIN.getCode());
        }
        Long memberId = JwtUtils.getMemberId(token);
        if (memberId == null) {
            throw new CartException("用户信息异常", BizCodeEnume.USER_LOGIN.getCode());
        }
        UserInfoTo userInfoTo = new UserInfoTo();
        userInfoTo.setUserId(memberId);
        toThreadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = toThreadLocal.get();
    }
}
